package core.lib;

import java.util.Hashtable;
import java.util.LinkedList;

import core.lib.interfaces.ICEventListener;
import core.lib.model.CoreEvent;
import core.lib.tools.CoreLog;

public class CoreEventDispatcher
{
	private Hashtable<String, LinkedList<ICEventListener>> mListeners = new Hashtable<>();

	public void registerCoreEventListener(String eventType, ICEventListener listener)
	{
		if (listener == null)
		{
			CoreLog.log(CoreLog.LEVEL_ERROR, CoreConstants.CORE_TAG, "null listener!");
		}

		synchronized (mListeners)
		{
			LinkedList<ICEventListener> l = mListeners.get(eventType);
			if (l == null)
			{
				l = new LinkedList<>();
				mListeners.put(eventType, l);
			}

			l.add(listener);
		}
	}

	public void unregisterCoreEventListener(String event, ICEventListener listener)
	{

	}

	public void handleCoreEvent(CoreEvent event)
	{
		boolean flag = false;
		synchronized (mListeners)
		{
			LinkedList<ICEventListener> list = mListeners.get(event.getType());
			if (list != null && list.size() > 0)
			{
				for (ICEventListener handler : list)
				{
					handler.handleEvent(event);
					flag = true;
				}

				if (!flag)
				{
					CoreLog.log(CoreLog.LEVEL_ERROR, CoreConstants.CORE_TAG, "No handler for the event : " + event.getType());
				}
			}
		}

	}
}
